package com.chx.service.Impl;

import com.chx.constant.MessageConstant;
import com.chx.constant.StatusConstant;
import com.chx.context.BaseContext;
import com.chx.dto.RolePermissionDto;
import com.chx.entity.Permissions;
import com.chx.entity.RolePermissions;
import com.chx.entity.Roles;
import com.chx.exception.AccountNotPowerException;
import com.chx.mapper.PermissionMapper;
import com.chx.mapper.RoleMapper;
import com.chx.service.PermissionService;
import com.chx.vo.PermissionVo;
import com.chx.vo.RolePermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author cp-月入过万
 * @Date 2025/5/30
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper  roleMapper;

    @Override
    public List<Permissions> getAllPermission() {
        return permissionMapper.getAllPermission();
    }

    @Override
    public void save(RolePermissionDto rolePermissionDto) {
        permissionMapper.delete(rolePermissionDto.getRoleId());
        for(Long permissionId : rolePermissionDto.getPermissionId()){
            RolePermissions rolePermissions =RolePermissions.builder()
                                                            .roleId(rolePermissionDto.getRoleId())
                                                            .permissionId(permissionId)
                                                            .build();
            if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN))
                permissionMapper.insert(rolePermissions);
            else
                throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
        }

    }

    @Override
    public RolePermissionVo getPermissionById(Long id) {
         Roles roles = roleMapper.getById(id);
         List<Permissions> permissions = permissionMapper.getPermissionById(id);

         if(roles != null && permissions != null){
             RolePermissionVo rolePermissionVo = new RolePermissionVo();
             rolePermissionVo.setRoleId(roles.getRoleId());
             rolePermissionVo.setRoleName(roles.getRoleName());
             List<PermissionVo> permissionVos = new ArrayList<>();
             for (Permissions permission : permissions) {
                 PermissionVo permissionVo = new PermissionVo();
                 permissionVo.setPermissionId(permission.getPermissionId());
                 permissionVo.setPermissionName(permission.getPermissionName());
                 permissionVos.add(permissionVo);
             }
             rolePermissionVo.setPermissionVos(permissionVos);
             return rolePermissionVo;
         }
         return null;
    }
}
